import Vue from 'vue';
import Vuex from 'vuex';
import { login, getInfo } from '@/api/system/user';  // 导入 getInfo 方法
import { getToken, setToken, removeToken } from "@/utils/auth"; // 添加 token 工具方法

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: getToken(),
    id: '',
    name: '',
    nickName: '',
    avatar: '',
    roles: [],
    permissions: [],
    isInfoLoaded: false
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      setToken(token);  // 使用统一的 token 设置方法
    },
    SET_USER_INFO: (state, data) => {
      // 将 API 返回的用户信息映射到 state
      state.id = data.userId || '';
      state.name = data.name || '';
      state.nickName = data.nickName || '';
      state.avatar = data.avatar || '';
      state.roles = data.roles || [];
      state.permissions = data.permissions || [];
      state.isInfoLoaded = true; // 设置已加载标志
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    LOGOUT: (state) => {
      state.token = '';
      state.id = '';
      state.name = '';
      state.nickName = '';
      state.avatar = '';
      state.roles = [];
      state.permissions = [];
      state.isInfoLoaded = false;
      removeToken();  // 使用统一的 token 移除方法
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      const { username, password, code, uuid } = userInfo;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
            .then(res => {
              commit('SET_TOKEN', res.token);  // 保存 token
              resolve();
            })
            .catch(error => {
              reject(error);
            });
      });
    },

    // 新增：获取用户信息
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
              const data = response.user || {};
              if (!data) {
                reject('验证失败，请重新登录');
              }
              commit('SET_USER_INFO', data);  // 保存用户信息
              resolve(data);
            })
            .catch(error => {
              reject(error);
            });
      });
    },

    logout({ commit }) {
      commit('LOGOUT');
    }
  }
});
